<template>
    <div class="updateGroupPolicy">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <!-- <el-breadcrumb-item>
                    <i class="el-icon-s-promotion"></i> 车辆配置
                </el-breadcrumb-item> -->
                <el-breadcrumb-item> 采集策略配置</el-breadcrumb-item>
                <el-breadcrumb-item> 更新组策略</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="content">
            <div class="main">
                <div>
                    <el-row>
                        <el-col :span="8" style="text-align: right;line-height: 40px">策略组ID：</el-col>
                        <el-col :span="8">
                            <el-input style="width: 100%" :model-value="groupId" disabled/>
                        </el-col>
                    </el-row>
                </div>
                <h3>配置策略组</h3>
                <div style="border:1px solid #eee;margin: 30px 0;">
                    <el-card shadow="hover" style="border-top:0;padding: 0 20px;">
                        <el-tree
                            ref="treeRef"
                            :props="defaultProps"
                            :data="groupPolicyTreeData"
                            node-key="id"
                            show-checkbox
                            @check-change="handleCheckChange"
                            :default-checked-keys="defaultChecked"
                        />
                    </el-card>
                </div>

                <h3 style="margin-bottom: 20px">已选策略</h3>
                <TableComponent v-loading="isLoading" element-loading-text="加载中..." :assetList="policyList"
                                :tableColumns="selectedPolicyTableColumns">
                    <template #priority="{ row }">
                        <span>{{ row.priority }}</span>
                    </template>
                    <template #status="{row}">
                        <span v-if="row.status === 0">暂停</span>
                        <span v-if="row.status === 1">启用</span>
                    </template>
                </TableComponent>
                <div style="text-align: center;margin: 15px">
                    <el-button type="primary" @click="submitFn">提交</el-button>
                </div>

            </div>
        </div>
    </div>
</template>

<script>

import {onMounted, reactive, ref, onActivated} from 'vue'

import {selectedPolicyTableColumns} from "@/constant/config.js";
import TableComponent from '@/components/TableComponent.vue';
import {getStrategyByGroupApi, getStrategyByIdsApi, editStrategyGroupApi} from "@/api/carManage/policyManage.js";
import _ from 'lodash';
import {ElMessage} from "element-plus";
export default {
    components: {
        TableComponent
    },
    setup() {
        const isLoading = ref(false)
        const policyList = ref([]);
        const groupPolicyTreeData = ref([]);
        const defaultChecked = ref([]);


        const getStrategyByGroupFn = () => {

            getStrategyByGroupApi({}).then(res => {

                if (res.data.code === 200) {
                    groupPolicyTreeData.value = transformData(res.data.data);
                }
            })

        }

        const transformData = (list) => {

            let transformList = [];

            list.forEach((item, index) => {
                transformList[index] = {

                    label: item.developDepartment,
                    children: transformScenesList(item.scenes)
                }


            })
            return transformList;
        }


        const transformScenesList = (list) => {
            let scenesList = [];
            list.forEach((item, index) => {
                scenesList[index] = {
                    sceneId: item.sceneId,
                    label: item.sceneName,
                    children: transformStrategiesList(item.strategies)
                }
            })
            return scenesList;
        }

        const transformStrategiesList = (list) => {
            let strategiesList = [];
            list.forEach((item, index) => {
                strategiesList[index] = {
                    id: item.id,
                    label: item.id + '-' + item.strategyName,
                }
            })
            return strategiesList;
        }

        const defaultProps = {
            children: 'children',
            label: 'label',
        }
        const treeRef = ref(null);

        const handleCheckChange = (data, checked, indeterminate) => {

            ids.value = _.compact(treeRef.value.getCheckedKeys());
            getStrategyByIdsTableFn();
        }


        const ids = ref([]);
        const getStrategyByIdsTableFn = () => {
            isLoading.value = true
            getStrategyByIdsApi({
                ids: ids.value
            }).then(res => {
                if (res.data.code === 200) {
                    policyList.value = res.data.data;
                    isLoading.value = false
                }
            })
        }
        const submitFn = () => {
            let userNo;
            try {
                userNo = JSON.parse(localStorage.getItem('userInfo')).employeeId;
            } catch (e) {
            }

            editStrategyGroupApi({
                userNo: userNo,
                id:groupId.value,
                strategyIds: ids.value
            }).then(res => {
                if (res.data.code === 200) {
                    ElMessage({
                        message: '修改成功',
                        type: 'success',
                    })
                    // 修改成功后更新策略组到sessionStorage
                   updatePolicyGroupRowDataSessionStorage()
                }else{
                    ElMessage({
                        message: '修改失败',
                        type: 'error',
                    })
                }
            })


        }
        const updatePolicyGroupRowDataSessionStorage = () => {
            let originData = JSON.parse(sessionStorage.getItem('policyGroupRowData'))
            let newData = originData
            newData.strategyIds = ids.value
            sessionStorage.setItem('policyGroupRowData', JSON.stringify(newData));
        }
        const groupId = ref('');
        onMounted(() => {
            getStrategyByGroupFn()

            try {
                defaultChecked.value =   JSON.parse(sessionStorage.getItem('policyGroupRowData')).strategyIds;
                groupId.value = JSON.parse(sessionStorage.getItem('policyGroupRowData')).id;
                ids.value= defaultChecked.value;
                getStrategyByIdsTableFn();
            } catch (e) {
            }

        })
        onActivated(() => {
           getStrategyByGroupFn()

            try {
                defaultChecked.value =   JSON.parse(sessionStorage.getItem('policyGroupRowData')).strategyIds;
                groupId.value = JSON.parse(sessionStorage.getItem('policyGroupRowData')).id;
                ids.value= defaultChecked.value;
                getStrategyByIdsTableFn();
            } catch (e) {
            }
        })

        return {
            defaultProps,
            handleCheckChange,
            selectedPolicyTableColumns,
            policyList,
            getStrategyByGroupFn,
            groupPolicyTreeData,
            treeRef,
            ids,
            submitFn,
            defaultChecked,
            groupId
        }
    }


}


</script>

<style lang="less">
.updateGroupPolicy {
    height: 100vh;

    .crumbs {
        display: flex;
        align-items: center;
        padding: 10px;
        margin-top: 5px;
    }

    .content {
        padding: 20px;
        background: #eeeeee;
        height: 100%;

        .main {
            padding: 20px;
            background: #FFFFFF;
            //display: flex;
            //justify-content: center;
        }

    }
}

</style>